from concurrent.futures.thread import ThreadPoolExecutor
from multiprocessing import Process

import json
import logging
import os
from requests_toolbelt.multipart.encoder import MultipartEncoder
import mimetypes

import time

import requests

from cn.boz.utils.Constants import Constants

appid = 'wx1042769b76361cb5'
secret = 'cb026be6635453bd7d24ba6917226764'
token_path = 'temp/access_token'

class UploadUtils:
    """
    文件上传工具
    """
    def __init__(self):
        # logging.basicConfig(level=logging.INFO,
        #                     format="%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")

        logger=logging.getLogger(UploadUtils.__name__)
        logger.setLevel(logging.INFO)
        self.logger=logger;
        """"""

    def __gettoken__(self):
        """
        从缓存路径获取token，主要存储于文件中
        :return:
        """
        try:
            fp = open(token_path)
            data = fp.read()
            return data
        finally:
            if fp != None:
                fp.close()
        return

    def getTokenInTime(self):
        """
        立即获取token,即将缓存文件作废
        :return:
        """
        stat = os.stat(token_path)
        mtime = stat.st_mtime
        elapse_time = time.time() - mtime
        logging.info('elapse time:%d'%(elapse_time))
        if elapse_time < 7000:
            return self.__gettoken__()
        logging.info('renew token')
        res = requests.get(
            'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (appid, secret))
        data = res.json()

        if 'errcode' not in data:
            access_token = data['access_token']
            with open(token_path, 'w+') as fp:
                fp.write(access_token)
                return self.__gettoken__()

    def uploadFile(self,uploadpath,filepath):
        """
        上传文件
        :param uploadpath: 上传到的路径
        :param filepath: 文件的全路径
        :return:
        """
        print("upload file%s"%(uploadpath))
        accessToken=self.getTokenInTime()
        res=requests.post("https://api.weixin.qq.com/tcb/uploadfile?access_token=%s"%(accessToken),json={
            'env': Constants.WX_ENV,
            'path': uploadpath
        })
        data=res.json()
        if data['errcode']==0:
            url=data['url']
            authorization=data['authorization']
            file_id=data['file_id']
            token=data['token']
            cos_file_id=data['cos_file_id']

            #比较麻烦
            m = MultipartEncoder(
                fields={
                    'Signature': authorization,
                    'key': uploadpath,
                    "x-cos-security-token": token,
                    "x-cos-meta-fileid": cos_file_id,
                    'file': ('filename', open(filepath, 'rb'), mimetypes.guess_type(filepath))}
            )
            res = requests.post(url, headers={
                "Content-Type":m.content_type
            }, data=m)

    def uploadDirectory(self,localdir,remotedir):
        """
        从本地目录上传到远程的目录
        假设本地目录是/a/b/c
        那么该目录下
        :param localdir:  本地目录
        :param remotedir:  远程目录
        :return:
        """
        if not os.path.exists(localdir):
            self.logger.warning("%s not exist!"%(localdir))

        if not os.path.isdir(localdir):
            self.logger.warning("%s is not directory!please use uploadFile() instead!"%(localdir))


            return





if __name__ == '__main__':

    uploadUtils=UploadUtils()
    uploadUtils.uploadDirectory("/Volumes/Mac/Code/pycharm/MyAI/cn","cn/")
    pass

    # basepath='/Users/blueboz/Desktop/20201205'
    # coms=os.listdir(basepath)
    # threadPool = ThreadPoolExecutor(max_workers=20, thread_name_prefix="test_")
    #
    # for com in coms:
    #     imgpath=os.path.join(basepath,com)
    #     if os.path.isdir(imgpath):
    #         files=os.listdir(imgpath)
    #         for file in files:
    #             print("up%s/%s"%(com,file))
    #             ig = UploadUtils()
    #             future = threadPool.submit(ig.uploadFile, 'commodity/%s/%s'%(com,file),os.path.join(imgpath,file))
    #
    # threadPool.shutdown(wait=True)
    # print("finished")

    # print(mimetypes.guess_type('aa.jpg'))
    # pass

# requests.post("https://api.weixin.qq.com/tcb/uploadfile?access_token=ACCESS_TOKEN",)
# POST https://api.weixin.qq.com/tcb/uploadfile?access_token=ACCESS_TOKEN
